package com.app.shop.service.system.impl;

import com.app.shop.util.SysModel;
import com.app.shop.dao.system.SysLogMapper;
import com.app.shop.dao.system.SysUserMapper;
import com.app.shop.entity.SysUser;
import com.app.shop.entity.SysUserExample;
import com.app.shop.entity.query.SysUserQuery;
import com.app.shop.service.system.SysUserService;
import com.app.shop.entity.show.SysUserShow;
import com.app.shop.util.ClassUtil;
import com.app.shop.util.PwdUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.Date;


/**
 * 系统用户操作
 *
 * @author chenliwei
 * @version v1.0 2019-3-11
 */
@Service("sysUserService")
public class SysUserServiceImp implements SysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImp.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysLogMapper sysLogMapper;

    @Override
    public Page<SysUser> getSysUserList(SysUserQuery studentQuery) {
        //查询条件
        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();
        //criteria.andStatusEqualTo(1);
        //用户名
        if (studentQuery.getName() != null && studentQuery.getName().trim().length() > 0) {
            criteria.andNameLike('%' + studentQuery.getName() + '%');
        }
        //用户状态
        if (studentQuery.getStatus() != null) {
            criteria.andStatusEqualTo(studentQuery.getStatus());
        }
        //用户账号
        if (studentQuery.getUsername() != null && studentQuery.getUsername().trim().length() > 0) {
            criteria.andUsernameLike('%' + studentQuery.getUsername() + '%');
        }
        //用户电话
        if (studentQuery.getPhone() != null && studentQuery.getPhone().trim().length() > 0) {
            criteria.andPhoneLike('%' + studentQuery.getPhone() + '%');
        }
        //模拟分页查询
        PageHelper.startPage(studentQuery.getCurrentPage(), studentQuery.getPageSize());
        return sysUserMapper.selectByExample(sysUserExample);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void resetUserPwd(SysUserQuery sysUserQuery) {
        //超级管理员不能被重置密码
        if (sysUserQuery.getUserId() != 1001) {
            SysUser sysUser = new SysUser();
            try {
                sysUser.setPassword(PwdUtil.encryptPassword("123456"));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            sysUser.setVersion(new Date());
            sysUser.setUserId(sysUserQuery.getUserId());
            sysUser.setUpdateUserId(sysUserQuery.getOptionUserId());
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }
    }

    @Override
    public SysModel editUserPwd(SysUserQuery sysUserQuery) {
        SysModel sysModel = new SysModel();
        //超级管理员不能被重置密码
        if (sysUserQuery.getUserId() != 1001) {
            //查询进行用户密码比对
            try {
                //查询用户是否存在
                SysUserExample sysUserExample = new SysUserExample();
                SysUserExample.Criteria criteria = sysUserExample.createCriteria();
                criteria.andUserIdEqualTo(sysUserQuery.getOptionUserId()).andPasswordEqualTo(PwdUtil.encryptPassword(sysUserQuery.getPassword()));
                Long cnt = sysUserMapper.countByExample(sysUserExample);
                if (cnt == 1) {
                    SysUser sysUser = new SysUser();
                    sysUser.setPassword(PwdUtil.encryptPassword(sysUserQuery.getPasswordNew()));
                    sysUser.setVersion(new Date());
                    sysUser.setUserId(sysUserQuery.getUserId());
                    sysUser.setUpdateUserId(sysUserQuery.getOptionUserId());
                    sysUserMapper.updateByPrimaryKeySelective(sysUser);
                    sysModel.setSuccess(true);
                } else {
                    sysModel.setSuccess(false);
                    sysModel.setMsg("修改失败，密码不正确不允许修改！");
                }
            } catch (Exception e) {
                sysModel.setSuccess(false);
                sysModel.setMsg("修改失败，修改密码过程发生异常请重试！");
                log.error("修改密码过程发生异常:" + e);
                e.printStackTrace();
            }
        } else {
            sysModel.setSuccess(false);
            sysModel.setMsg("修改失败，超级管理员不允许被修改！");
        }
        return sysModel;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateUserStart(SysUserQuery sysUserQuery) {
        //超级管理员不能被重新启用或者禁用
        if (sysUserQuery.getUserId() != 1001) {
            SysUser sysUser = new SysUser();
            sysUser.setStatus(1);
            sysUser.setVersion(new Date());
            sysUser.setUserId(sysUserQuery.getUserId());
            sysUser.setUpdateUserId(sysUserQuery.getOptionUserId());
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateUserStop(SysUserQuery sysUserQuery) {
        //超级管理员不能被重新启用或者禁用
        if (sysUserQuery.getUserId() != 1001) {
            SysUser sysUser = new SysUser();
            sysUser.setStatus(-1);
            sysUser.setVersion(new Date());
            sysUser.setUserId(sysUserQuery.getUserId());
            sysUser.setUpdateUserId(sysUserQuery.getOptionUserId());
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }
    }

    @Override
    public SysUserShow getUserInfo(SysUserQuery sysUserQuery) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(sysUserQuery.getUserId());
        SysUserShow sysUserShow = new SysUserShow();
        try {
            ClassUtil.fatherToChild(sysUser, sysUserShow);
            //码表值补全
            sysUserShow.dataSet();
        } catch (Exception e) {
            log.error("用户信息补全码表过程中发生异常:" + e);
            e.printStackTrace();
        }
        return sysUserShow;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SysModel addUserInfo(SysUser sysUser) {
        SysModel sysModel = new SysModel();
        try {
            //查询用户是否存在
            SysUserExample sysUserExample = new SysUserExample();
            SysUserExample.Criteria criteria = sysUserExample.createCriteria();
            criteria.andUsernameEqualTo(sysUser.getUsername());
            sysUser.setCreateDate(new Date());
            sysUser.setVersion(new Date());
            //密码加密
            sysUser.setPassword(PwdUtil.encryptPassword(sysUser.getPassword()));
            Long cnt = sysUserMapper.countByExample(sysUserExample);
            if (cnt < 1) {
                sysUserMapper.insert(sysUser);
                sysModel.setSuccess(true);
            } else {
                sysModel.setSuccess(false);
                sysModel.setMsg("添加失败，用户已经存在！");
            }
        } catch (Exception e) {
            sysModel.setSuccess(false);
            sysModel.setMsg("添加失败，添加用户过程发生异常请重试！");
            log.error("用户添加过程中发生异常:" + e);
            e.printStackTrace();
        }
        return sysModel;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SysModel updateUserInfo(SysUser sysUser) {
        SysModel sysModel = new SysModel();
        if (sysUser.getUserId() != 1001) {
            try {
                // 修改要和之前的版本时间对应，不然不允许修改
                SysUserExample sysUserExample = new SysUserExample();
                SysUserExample.Criteria criteria = sysUserExample.createCriteria();
                criteria.andUserIdEqualTo(sysUser.getUserId()).andVersionEqualTo(sysUser.getVersion());
                SysUser sysUserUp = sysUserMapper.selectByPrimaryKey(sysUser.getUserId());
                if (sysUserUp != null) {
                    sysUserUp.setStatus(sysUser.getStatus());
                    sysUserUp.setEmail(sysUser.getEmail());
                    sysUserUp.setName(sysUser.getName());
                    sysUserUp.setRemark(sysUser.getRemark());
                    sysUserUp.setPhone(sysUser.getPhone());
                    sysUserUp.setSex(sysUser.getSex());
                    sysUserUp.setVersion(new Date());
                    sysUserUp.setUpdateUserId(sysUser.getUpdateUserId());
                    sysUserMapper.updateByExample(sysUserUp, sysUserExample);
                    sysModel.setSuccess(true);
                } else {
                    sysModel.setSuccess(false);
                    sysModel.setMsg("修改失败，当前信息已经被他人修改请重试！");
                }
            } catch (Exception e) {
                sysModel.setSuccess(false);
                sysModel.setMsg("修改失败，修改过程发生异常请重试！");
                log.error("用户修改过程中发生异常:" + e);
                e.printStackTrace();
            }
        } else {
            sysModel.setSuccess(false);
            sysModel.setMsg("修改失败，超级管理员不允许被修改！");
        }
        return sysModel;
    }
}
